<template  >
    <div class="white-module module" v-loading="loading">

      <div class="title"><span></span>参赛信息</div>
      <div class="info">
        <div class="item">
         <div class="o"> <span>参与代表队</span>{{teaminfo.team_name}}</div>
        </div>
        <div class="item">
          <div class="o">  <span>领队</span>{{teaminfo.real_name}}</div>
        </div>



      </div>

      <div class="title"><span></span>赛事信息</div>
      <div class="info">
        <div class="item">
         <div class="o"> <span>参与赛事</span>{{matchInfo.matchName}}</div>

            <span class="last" v-if="record.typename!=='个人赛'">参赛队伍</span>
            <el-input v-if="record.status==5&&record.typename!=='个人赛'&&type=='rise'" v-model="record.team_name" style="width: 120px"></el-input>
            <label v-else-if="record.typename!=='个人赛'">{{record.team_name}}</label>

        </div>
        <!--推荐晋级（选手不可更换，老师有一次更换机会）
        <div class="item">
          <div class="o">
            <span>参与赛项</span>{{record.item_name}}
          </div>
          <span class="last">指导老师</span>{{record.teachers}}
        </div>
        -->
        <div class="item">
          <div class="o">
            <span>参与赛项</span>{{record.item_name}}
          </div>
          <span class="last">指导老师</span>{{record.zdlsStr}}
          <!--获晋级资格，只有一次机会 record.status==5 &&-->
          <el-button v-if="matchInfo.matchLevel = 1 && record.status==0 && record.teacher_upd_times<1" type="primary" @click="showUpdTeacherDialog">修改指导老师</el-button>
        </div>

        <div class="item">
          <div class="o"> <span>参赛组别</span>{{record.group_name}}</div><span class="last"
            >比赛时间</span
          >{{matchInfo.matchDate}}
        </div>

        <div class="item">
          <div class="o">  <span>参赛选手</span>
            <el-checkbox-group v-model="checkList" v-if="((record.status==5 && type=='rise' ) || (matchInfo.matchLevel = 1 && record.status==0))&& record.typename!=='个人赛'">

            <div v-for="user in users">
              <el-checkbox  :label="user.code" :key="user.code">{{user.name}}</el-checkbox>
            </div>

          </el-checkbox-group>
            <label v-else>{{record.real_name}}</label>
          </div>
          <span class="last"
            >报名时间</span
          >{{record.create_date}}
        </div>
      </div>

      <!--此处注意：晋级和详情用的同一个页面-->
      <!--只有国赛、或者省赛晋级这两种情况显示报名表-->
      <div class="title" v-if="matchInfo.matchLevel=='1' || (matchInfo.matchLevel=='2' && type=='rise')"><span></span>赛项报名表</div>
      <div class="info" v-if="matchInfo.matchLevel=='1' || (matchInfo.matchLevel=='2' && type=='rise')">

        <div class="item" style="margin-left: 100px">
          <!--① 以获晋级资格且点击确认晋级页面 ②状态为“审核中”和“报名成功”时，且重传次数未达到上线，可二次重传-->
          <el-upload
              :disabled="(record.status==5 && type=='rise') || ((record.status==0 || record.status==1) && sysParams.isReUploadFile=='1' && record.rise_times < sysParams.reUploadTimes) ? false : true"
              class="avatar-uploader"
              :action="baseUrl+'/front/upload'"
              :show-file-list="false"
              :on-success="handleAvatarSuccess2"
              :before-upload="beforeAvatarUpload2"
              ref="upload"
          >
            <label v-if="!record.rise_file&& type=='rise'" style="color: red;">*</label>
            <div class="image image1">
              <img v-if="record.rise_file" :src="record.rise_file_show" class="img" />
              <div v-else-if="type=='rise'" class="upload ">
                <img src="@/assets/common/upload.png">
                <div class="text">赛项报名表</div>
              </div>
              <div class="text" style="color: #72767b;cursor: auto;" v-if="(record.status==0 || record.status==1) && sysParams.isReUploadFile=='1' && record.rise_times < sysParams.reUploadTimes">点击报名表重新上传</div>
              <p v-if="!(record.status==5 && type=='rise') && record.rise_file"><a target="_blank" style="text-decoration: underline; color: #00a0e9;" @click.stop="downLoad1()">查看参赛报名表</a></p>
            </div>
          </el-upload>
          <br/>
          <!--
          &nbsp;&nbsp;&nbsp;&nbsp;
          <p v-if="!(record.status==5 && type=='rise')"><a target="_blank" style="text-decoration:underline;color: #00a0e9;cursor:pointer;" @click.stop="downLoad1()">查看参赛报名表</a></p>
          -->
        </div>
      </div>

      <!--状态为“审核中”和“报名成功”时，且开启了全局重传，且重传次数未达到上线，晋级操作时才显示-->
      <div v-if="(record.status==0 || record.status==1) && sysParams.isReUploadFile=='1' && record.rise_times < sysParams.reUploadTimes && matchInfo.matchLevel=='1'">
        <el-form style="margin-left: 30%">
          <el-form-item>
            <div class="btns">
              <el-button type="primary" @click="reRiseFileHandle">
                确认提交
              </el-button>
              <el-button @click="back">返回</el-button>
              <p>备注：仅可修改一次！！</p>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="title" v-if="record.score_open==1"><span></span>成绩信息</div>
      <div class="info" v-if="record.score_open==1">
        <div class="item">
          <div class="o" style="width: 600px;"> <span style="font-weight: bold;">成绩</span><div v-html="scoreResut.score"></div></div>
        </div>
        <div class="item">
          <div class="o" style="width: 600px;"> <span style="font-weight: bold;">名次</span><div v-html="scoreResut.ranks"></div></div>
        </div>
        <div class="item">
          <div class="o" style="width: 600px;"> <span style="font-weight: bold;">奖等</span>
            <!--国赛不显示奖等
            <div v-if="matchInfo.matchLevel!='1'" v-html="scoreResut.grade"></div>
            -->
            <div v-html="scoreResut.grade"></div>
          </div>
        </div>
      </div>

      <div  v-if="(record.status==5 && type=='rise')" class="title">
        <el-form style="margin-left: 30%">
          <el-form-item>

            <div class="btns">
              <el-button @click="back">取消</el-button>
              <el-button type="primary" @click="risehandle">
                提交
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!--
      <div class="hint">
          注：<div>
            赛前请关注 参赛报名 > 报名记录 > 对应赛事赛项的参赛时间信息；<br/>赛前请关注 参赛报名 > 报名记录 > 对应赛事赛项的抽签信息。
          </div>
      </div>
      -->
      <!--修改指导老师弹窗-->
      <el-dialog v-model="updTeacherVisible" title="修改指导老师" style="width: 600px; height: 350px;" >
        <el-form style="margin-left: 10%">
          <el-form-item>
            <div class="item">
              <span><span>*</span>原指导老师：</span>
              {{record.zdlsStr}}
            </div>
          </el-form-item>
          <el-form-item>
            <div class="item">
              <span><span>*</span> 指导老师：</span>
              <el-cascader style="width:241px"
                           v-model="updTeacherForm.teachers" :options="teacherList" :props="{ multiple: true }"
                           collapse-tags collapse-tags-tooltip :show-all-levels="false" @change="checkTeacher"/>
              <span style="color:red;text-align:left;font-size: 12px;margin-left: 10px">{{updTeacherForm.teacherMsg}}</span>
            </div>
          </el-form-item>
          <el-form-item>
            <div class="btns">
              <el-button @click="back">取消</el-button>
              <el-button type="primary" @click="submitUpdTeacher">提交</el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </template>

<script lang="ts">

import {defineComponent, reactive, toRefs, ref, onMounted} from "vue";
import baseService from "@/service/baseService";
import app from "@/constants/app";
import {ElMessage, UploadProps} from "element-plus";
import router from "@/router";

export default defineComponent({

  mounted() {
    this.id = this.$route.query.id;
    this.type = this.$route.query.type;
    this.querySysParams();
    this.queryInfo();
    this.queryScore();
  },

  data() {
    return {
      updTeacherVisible: false,
      users: [{name: "", code: ""}],
      checkList: [] as any,
      loading: false,
      type: null as any,
      baseUrl: app.api,
      id: null as any,
      teaminfo: {
        real_name: "",
        team_name: ""
      },
      record: {
        create_date: '',
        rise_file: '',
        rise_file_old: '',
        rise_times: '',
        rise_file_show: '',
        user_ids: '',
        classname: "创意类",
        group_name: "初中组",
        teachers: "姓名7",
        item_name: "团体花样表演",
        real_name: "王莉莉、张悦悦、宋婷婷",
        id: "1655117165470240769",
        typename: "团体赛",
        team_name: "214234",
        zdlsStr: '',
      },
      matchInfo: {
        matchName: '',
        matchLevel: '',
        beginSignup: '',
        beginDate: '',
        matchDate: '',
        signupDate: '',
      },
      sysParams: {
        isReUploadFile: '',
        reUploadTimes: '',
      },
      scoreResut: {
        score: '',
        ranks: '',
        grade: ''
      },
      reUploadFlag: false,
      teacherList:[ {
        value: 'guide',
        label: 'Guide'}
      ],
      updTeacherForm: {
        teachers: [],
        teacherMsg: '',
        matchiteminfo: {
          teacher_num: 0,
          teacher_num_max: 0
        }
      },
    };
  },

  methods: {
    queryMatch(id: string) {
      baseService.get('/front/spmatch/info/' + id).then(e => {
        this.matchInfo = e.data;
      })
    },
    //查询赛项信息
    queryMatchItem(itemId:string) {
      baseService.get("/front/fast/match/matchItem/info?id=" + itemId).then((e: any) => {
        if (e.code == '0') {
          this.updTeacherForm.matchiteminfo = e.data;
        }
      });
    },
    querySysParams() {
      baseService.get('/front/spmatch/sysParams').then(e => {
        this.sysParams = e.data;
      })
    },
    queryScore() {
      baseService.get('/front/spmatchItemTeam/queryScore?id=' + this.id).then(e => {
        this.scoreResut = e.data;
      })
    },
    queryInfo() {
      if(!this.id){
        return;
      }
      baseService.get('/front/fast/match/matchRecordItem/info?myinfo=1&id=' + this.id).then(e => {
        this.record = e.data;
        this.record.rise_file_show = this.record.rise_file;
        this.record.rise_file_old = this.record.rise_file;
        if (this.record.rise_file && this.record.rise_file.toLowerCase().includes(".pdf")) {
          this.record.rise_file_show = "http://img.fii-cc.com/fii/20230604/b2f13f0061e14463b63683f3998f055a.jpg";
        }
        const names = this.record.real_name.split("、")
        const ids = this.record.user_ids.split("、");
        this.users = [];
        for (let i = 0; i < names.length; i++) {
          this.users.push({name: names[i], code: ids[i]});
          this.checkList.push(ids[i]);
        }
        //获取指导老师
        const zdls = this.record.teachers.split(",");
        if(zdls.length>1){
          this.record.zdlsStr = zdls[0];
          console.log(zdls[1]);
          for(let i=0;i<zdls[0].length;i++){
            this.record.teachers = zdls[i];
          }
        }
        this.queryMatch(e.data.match_id);
        this.queryMatchItem(e.data.match_item_id);
        this.queryTeamInfo(e.data.team_id);
      })
    }
    //查询赛项信息
    , queryTeamInfo(id: any) {
      baseService.get("/front/fast/user/team/info?id=" + id).then((e: any) => {
        if (e.code == '0') {
          this.teaminfo = e.data;
        }
      });
    }
    , beforeAvatarUpload2(rawFile: any) {
      if (!(rawFile.type == 'image/jpeg' || rawFile.type == 'image/png' || rawFile.type == 'image/jpg' || rawFile.type == 'pdf/pdf')) {
        //ElMessage.error('仅支持JPG/JPEG/PNG/PDF格式!')
        //return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件超过2MB!')
        return false
      }
      return true
    }, handleAvatarSuccess2(
        response: any,
        uploadFile: any
    ) {
      this.record.rise_file = response.data.src;
      this.record.rise_file_show = response.data.showSrc ? response.data.showSrc : response.data.src;
      //ruleForm.empower = response.data.src;
      //imageUrl2.value = URL.createObjectURL(uploadFile.raw!)
    },
    downLoad1() {
      window.open(this.record.rise_file);
      return;
      let a = document.createElement('a');
      let evt = document.createEvent('MouseEvents');
      a.download = '晋级列表';
      a.href = app.api + "/front/download?imageUrl=" + this.record.rise_file;
      evt.initEvent('click', true, true);
      a.dispatchEvent(evt);
      window.URL.revokeObjectURL(a.href);
    },
    back() {
      //router.push("/enroll/enrollList");
      //后退
      window.history.go(-1);
    },
    /**
     * 晋级
     * @param id
     */
    risehandle(id: any) {
      if (!this.record.rise_file && this.matchInfo.matchLevel == '2') {
        ElMessage.error("请上传赛项报名表！");
        return;
      }
      this.loading = true;
      baseService.get("/front/spmatchItemTeam/rise?id=" + this.id + "&riseFile=" + this.record.rise_file + "&users=" + this.checkList.join(",") + "&groupName=" + this.record.team_name).then((res: any) => {
        this.loading = false;
        if (res.code == 0) {
          ElMessage.success('申请成功');
          router.push("/enroll/enrollList");
        } else {
          ElMessage.error(res.msg);
        }
      })
    },
    reRiseFileHandle() {
      if (!this.record.rise_file) {
        ElMessage.error("请上传赛项报名表！");
        return;
      }

      if(this.record.rise_file == this.record.rise_file_old){
        ElMessage.error("未重传报名表，无须提交！");
        return;
      }

      baseService.get("/front/spmatchItemTeam/reUploadRiseFile?id=" + this.id + "&riseFile=" + this.record.rise_file + "&users=" + this.checkList.join(",")).then((res: any) => {
        this.loading = false;
        if (res.code == 0) {
          ElMessage.success('重新上传报名表成功');
          router.push("/enroll/enrollList");
        } else {
          ElMessage.error(res.msg);
        }
      })
    },
    // 弹出修改老师弹窗
    showUpdTeacherDialog() {
      this.queryTeacher();
      this.updTeacherVisible = true;
    },
    // 查询指导老师
    queryTeacher: function () {
      baseService.get("/front/fast/user/userList/list?pageSize=10&type=3").then(e => {
        this.teacherList = [];
        interface SpUser{id:string,real_name:string};
        e.data.forEach((e2:SpUser) => {
          this.teacherList.push( {
            value: e2.id,
            label: e2.real_name});
        });
      });
    },
    // 选择老师需要校验数量
    checkTeacher() {
      // 选择的老师数量
      const teacherLen = this.updTeacherForm.teachers.length;
      // 赛项要求的老师数量-最小
      const teacherNumMin = this.updTeacherForm.matchiteminfo.teacher_num;
      // 赛项要求的老师数量-最大
      const teacherNumMax = this.updTeacherForm.matchiteminfo.teacher_num_max;
      if (teacherLen < teacherNumMin || teacherLen > teacherNumMax) {
        if (teacherNumMin == teacherNumMax) {
          this.updTeacherForm.teacherMsg = "请选择" + teacherNumMin + "位老师";
        } else {
          this.updTeacherForm.teacherMsg = "请选择" + teacherNumMin + "~" + teacherNumMax + "位老师";
        }
      } else {
        this.updTeacherForm.teacherMsg = "";
      }
    },
    // 确认修改老师
    submitUpdTeacher() {
      // 验证是否选择了老师
      if (this.updTeacherForm.teachers.length == 0) {
        ElMessage.error("请选择指导老师");
        return;
      }
      // 验证有错误消息不能提交
      if (this.updTeacherForm.teacherMsg) {
        return;
      }
      const teacherIds = this.updTeacherForm.teachers.join(",");
      baseService.post(
          "/front/spmatchItemTeam/updateTeacher",
          {
            id: this.id,
            teachers: teacherIds
          }
      ).then((res: any) => {
        if (res.code == 0) {
          ElMessage.success('修改指导老师成功');
          this.updTeacherVisible = false;
          this.queryInfo();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }


  }
});
</script>

<style lang="scss" scoped>
.img{
  width: 100px;

}
.module {
  padding: 20px 0px 50px;
  margin-bottom: 12px;
  position: relative;

  .title {
    display: flex;
    align-items: center;
    font-size: 16px;
    font-weight: $font-weight-bold;
    padding: 0px 24px;

    span {
      width: 4px;
      height: 12px;
      background: #00a0e9;
      margin-right: 7px;
    }
  }


  .info {
    margin-bottom: 34px;
    padding-top: 1px;
    margin-top: 4px;

    .item {
      display: flex;
      align-items: center;
      margin-top: 8px;
      color: #4f5a70;

      .o {
        width: 400px;
        display: flex;
      }

      span {
        width: 78px;
        margin-left: 35px;
        text-align: right;
        margin-right: 20px;
      }
    }
  }


  .hint {
    width: 740px;
    margin: 54px 0px 20px;
    color: #959CA9;
    font-size: 12px;
    display: flex;
    line-height: 17px;
    justify-content: flex-end;
  }

}
</style>
